import wave

import pyaudio


def convert_content(content, options):
    new_content = []

    for item in content:
        if item["type"] == 1:  # 普通文本
            new_content.append({
                "type": 1,
                "text": item["text"]
            })
        elif item["type"] == 2:  # 对话文本
            new_content.append({
                "type": 2,
                "text": "",
                "name": item["name"],
                "dialogue": item["dialogue"],
                "voice_type": item["voice_type"]
            })

    # 添加选项部分
    if options:
        new_content.append({"type": "options", "options": options})

    return new_content

class SoundPlayer:
    def __init__(self, file_path):
        self.file_path = file_path

    def play(self):
        try:
            # 打开WAV文件
            wf = wave.open(self.file_path, 'rb')
            # 初始化PyAudio
            p = pyaudio.PyAudio()
            # 打开流
            stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                            channels=wf.getnchannels(),
                            rate=wf.getframerate(),
                            output=True)
            # 读取数据并播放
            data = wf.readframes(1024)
            while len(data) > 0:
                stream.write(data)
                data = wf.readframes(1024)
            stream.stop_stream()
            stream.close()
            p.terminate()
        except wave.Error as e:
            print(f"Wave file error: {e}")
        except pyaudio.PyAudioError as e:
            print(f"PyAudio error: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")


def sound_play():
    file_path = 'demo.wav'
    # print(file_path)
    player = SoundPlayer(file_path)
    player.play()
